package cn.com.miao.lynx.common.base.controller;

import cn.com.miao.lynx.common.core.model.PageParam;
import cn.com.miao.lynx.common.core.model.Result;
import cn.hutool.core.util.StrUtil;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;

/**
 * CommonController
 *
 * @title: CommonController
 * @description:
 * @author: dengmiao
 * @create: 2019-12-23 17:06
 **/
public interface CommonController {

    /**
     * 包装result
     * @param result 待包装的result
     * @return ResponseEntity
     */
    default ResponseEntity<Result> wrap(Result result) {
        return Result.wrap(result);
    }

    /**
     * 成功
     * @param data 响应数据
     * @return ResponseEntity
     */
    default ResponseEntity<Result> ok(Object data) {
        return wrap(Result.ok(data));
    }

    /**
     * 失败
     * @param msg 失败的描述
     * @return ResponseEntity
     */
    default ResponseEntity<Result> fail(String msg) {
        return wrap(Result.error(msg));
    }

    /**
     * 失败
     * @param code 失败的响应状态码
     * @param msg 失败的描述
     * @return ResponseEntity
     */
    default ResponseEntity<Result> fail(int code, String msg) {
        return wrap(Result.error(code, msg));
    }

    /**
     * 分页参数toPageable
     * @param page 分页参数
     * @return Pageable
     */
    default Pageable toPageAble(PageParam page) {
        Pageable pageable;
        int pageNumber = page.getPageNo();
        int pageSize = page.getPageSize();
        String sort = page.getSort();
        String order = page.getOrder();

        if(pageNumber < 1){
            pageNumber = 1;
        }
        if(pageSize < 1){
            pageSize = 10;
        }
        if(StrUtil.isNotBlank(sort)) {
            Sort.Direction d;
            if(StrUtil.isBlank(order)) {
                d = Sort.Direction.DESC;
            }else {
                d = Sort.Direction.valueOf(order.toUpperCase());
            }
            Sort s = Sort.by(d, sort);
            pageable = PageRequest.of(pageNumber - 1, pageSize, s);
        } else {
            pageable = PageRequest.of(pageNumber - 1, pageSize);
        }
        return pageable;
    }
}
